package com.sddongyun.proxy;

import com.sddongyun.common.JaxWsDynamicClientFactory;
import com.sddongyun.config.ProxConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.mitre.dsmiley.httpproxy.ProxyServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Created by lenovo on 2019-11-30.
 */
@Slf4j
public class CxfProxyServlet extends ProxyServlet{

    JaxWsDynamicClientFactory clientFactory= ProxConfig.getJaxWsDynamicClientFactory();

    Client client;

    @Override
    public void init() throws ServletException {

        targetUri = getConfigParam(P_TARGET_URI);
        client=clientFactory.createClient(targetUri);

        HTTPConduit conduit=(HTTPConduit)client.getConduit();
        HTTPClientPolicy policy=new HTTPClientPolicy();
        policy.setConnectionTimeout(30000);
        policy.setReceiveTimeout(30000);
        policy.setConnectionRequestTimeout(30000);
        conduit.setClient(policy);
    }

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {
        String methodName=servletRequest.getParameter("soap_method");
        String input = servletRequest.getParameter("input");
        //RequestCode  RequestXML
        String RequestCode=servletRequest.getParameter("RequestCode");
        String RequestXML=servletRequest.getParameter("RequestXML");

        log.info("targetUri: "+ targetUri);
        log.info("输入：methodName: "+methodName );
        log.info("输入：input: "+input );
        log.info("输入：RequestCode: "+RequestCode );
        log.info("输入：RequestXML: "+RequestXML );
        try {
            Object[] response=null;
            if(null!=RequestCode){
               //如果返回的address不是远程服务地址，重新制定地址
               client.getEndpoint().getEndpointInfo().setAddress(targetUri.replace("?wsdl",""));
               response=client.invoke(methodName,RequestCode,RequestXML);
            }else{
               client.getEndpoint().getEndpointInfo().setAddress(targetUri.replace("?wsdl",""));
               response= client.invoke(methodName,input);
            }
            String out = response[0].toString();
            servletResponse.getOutputStream().write(out.getBytes("utf-8"));
            log.info("输出："+out);
//            servletResponse.setCharacterEncoding("utf-8");
//            servletResponse.getWriter().write(response[0].toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void destroy() {
        client.destroy();
    }
}
